/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package GUI;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;

/**
 *
 * @author Manuel
 */
public class Utilities {

    public static void log(String content){
        if(!new File("log").exists()){
            try {
            new File("log").createNewFile();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        try {
            FileWriter fstream;
            fstream = new FileWriter("log",true);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(content);
            out.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    public static String getPage(String u){

        long elapsedTime = System.currentTimeMillis();
        String page ="";
        boolean success = false;
        int trials = 0;
        while(!success && trials < 3){
            try {
                URL url = new URL(u);
                URLConnection uc = url.openConnection();
                uc.addRequestProperty("Host", "code.google.com");
                BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
                String str;
                while ((str = in.readLine()) != null) {
                    page = page + str;
                }
                success = true;
            } catch (Exception ex) {
                trials++;
            }
        }
        if(!success)
            System.err.println("Cannot reach the requested page "+u+ " wrong url or missing connection");
        System.out.println("Retrieved page in "+(System.currentTimeMillis()-elapsedTime)+"ms");
        return page;
    }

}
